﻿using System.Data;
using System.Linq;
using System.Web.Mvc;
using MenuPlanner.Models;

namespace MenuPlanner.Controllers
{
  [Authorize(Roles="Menu Admins")]
  public class MenuAdminController : Controller
  {
    private RestaurantEntities db = new RestaurantEntities();

    //
    // GET: /Admin/
    public ActionResult Index()
    {
      var menus = db.Menus.Include("MenuCard");
      return View(menus.ToList());
    }

    //
    // GET: /Admin/Details/5
    public ActionResult Details(int id = 0)
    {
      Menu menu = db.Menus.Single(m => m.Id == id);
      if (menu == null)
      {
        return HttpNotFound();
      }
      return View(menu);
    }

    //
    // GET: /Admin/Create

    public ActionResult Create()
    {
      ViewBag.MenuCardId = new SelectList(db.MenuCards, "Id", "Name");
      return View();
    }

    //
    // POST: /Admin/Create

    [HttpPost]
    public ActionResult Create(Menu menu)
    {
      if (ModelState.IsValid)
      {
        db.Menus.AddObject(menu);
        db.SaveChanges();
        return RedirectToAction("Index");
      }

      ViewBag.MenuCardId = new SelectList(db.MenuCards, "Id", "Name", menu.MenuCardId);
      return View(menu);
    }

    //
    // GET: /Admin/Edit/5

    public ActionResult Edit(int id = 0)
    {
      Menu menu = db.Menus.Single(m => m.Id == id);
      if (menu == null)
      {
        return HttpNotFound();
      }
      ViewBag.MenuCardId = new SelectList(db.MenuCards, "Id", "Name", menu.MenuCardId);
      return View(menu);
    }

    //
    // POST: /Admin/Edit/5

    [HttpPost]
    public ActionResult Edit(Menu menu)
    {
      if (ModelState.IsValid)
      {
        db.Menus.Attach(menu);
        db.ObjectStateManager.ChangeObjectState(menu, EntityState.Modified);
        db.SaveChanges();
        return RedirectToAction("Index");
      }
      ViewBag.MenuCardId = new SelectList(db.MenuCards, "Id", "Name", menu.MenuCardId);
      return View(menu);
    }

    //
    // GET: /Admin/Delete/5

    public ActionResult Delete(int id = 0)
    {
      Menu menu = db.Menus.Single(m => m.Id == id);
      if (menu == null)
      {
        return HttpNotFound();
      }
      return View(menu);
    }

    //
    // POST: /Admin/Delete/5

    [HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(int id)
    {
      Menu menu = db.Menus.Single(m => m.Id == id);
      db.Menus.DeleteObject(menu);
      db.SaveChanges();
      return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
      db.Dispose();
      base.Dispose(disposing);
    }
  }
}